package com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.auth.entity.Node;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.appDynamic.entity.resp.UserInfoResp;
import com.xyht.sca_s.student_manage_system.modules.org.entity.SmsOrgStructure;
import com.xyht.sca_s.student_manage_system.modules.org.mapper.SmsOrgStructureMapper;
import com.xyht.sca_s.student_manage_system.modules.org.util.NodeTreeUtil;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsStudentInfo;
import com.xyht.sca_s.student_manage_system.modules.student.entity.SmsUserStudentRelation;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsStudentInfoMapper;
import com.xyht.sca_s.student_manage_system.modules.student.mapper.SmsUserStudentRelationMapper;
import com.xyht.sca_s.student_manage_system.modules.user.entity.SmsUser;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.SmsWnsInformationConsult;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.req.SmsWnsInformationConsultReq;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.SmsWnsInformationConsultResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.entity.resp.SmsWnsMyInformationConsultResp;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.mapper.SmsWnsInformationConsultMapper;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.service.SmsWnsInformationConsultService;
import com.xyht.sca_s.student_manage_system.modules.welcomeNewStudent.util.AssistantUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;

/**
 * <p>
 * 信息咨询群表 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2024-01-25
 */
@Service
public class SmsWnsInformationConsultServiceImpl extends ServiceImpl<SmsWnsInformationConsultMapper, SmsWnsInformationConsult> implements SmsWnsInformationConsultService {

    @Resource
    private SmsWnsInformationConsultMapper smsWnsInformationConsultMapper;
    @Resource
    private SmsStudentInfoMapper smsStudentInfoMapper;
    @Resource
    private SmsUserStudentRelationMapper smsUserStudentRelationMapper;
    @Resource
    private AssistantUtil assistantUtil;
    @Resource
    private SmsOrgStructureMapper orgStructureMapper;
    @Resource
    private NodeTreeUtil nodeTreeUtil;

    @Override
    public ResponseResult addInformationConsult(String userId, SmsWnsInformationConsultReq addReq) {
        if (isNullOrEmpty(addReq.getCollegeId(),addReq.getCollegeName(),addReq.getMajorName(),addReq.getMajorId(),addReq.getGradeId(),
                addReq.getGradeName(),addReq.getClassId(),addReq.getClassName(),addReq.getQrCode(),addReq.getQrNumber())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        List<SmsWnsInformationConsult> informationConsultList = smsWnsInformationConsultMapper.selectList(new LambdaQueryWrapper<SmsWnsInformationConsult>()
                .eq(SmsWnsInformationConsult::getCollegeId, addReq.getCollegeId())
                .eq(SmsWnsInformationConsult::getMajorId, addReq.getMajorId())
                .eq(SmsWnsInformationConsult::getGradeId, addReq.getGradeId())
                .eq(SmsWnsInformationConsult::getClassId, addReq.getClassId()));
        if (!informationConsultList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INFORMATION_CONSULT_EXIST);
        }
        //校验院 专业 年级 班级
        QueryWrapper<SmsOrgStructure> orgWrapper = new QueryWrapper<>();
        List<SmsOrgStructure> orgList = orgStructureMapper.selectList(orgWrapper);
        orgWrapper.lambda().eq(SmsOrgStructure::getOrgName, addReq.getCollegeName());
        SmsOrgStructure collegeOrg = orgStructureMapper.selectOne(orgWrapper);
        if (collegeOrg == null) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_COLLEGE_NOT_EXIST);
        }
        List<Node> nodeList = new ArrayList<>();
        for (SmsOrgStructure structure : orgList) {
            Node node = new Node();
            BeanUtils.copyProperties(structure, node);
            nodeList.add(node);
        }
        Node collegeNode = nodeTreeUtil.getChildNodesTree(nodeList, collegeOrg.getId());
        List<Node> childNode = collegeNode.getChildNodeList();
        List<Node> majorNode = childNode.stream()
                .filter(node -> node.getOrgName().equals(addReq.getMajorName()))
                .collect(Collectors.toList());
        if (majorNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_MAJOR_NOT_EXIST);
        }
        List<Node> gradeNode = majorNode.get(0).getChildNodeList().stream()
                .filter(node -> node.getOrgName().equals(addReq.getGradeName()))
                .collect(Collectors.toList());
        if (gradeNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_GRADE_NOT_EXIST);
        }
        List<Node> classNode = gradeNode.get(0).getChildNodeList().stream()
                .filter(node -> node.getOrgName().equals(addReq.getClassName()))
                .collect(Collectors.toList());
        if (classNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_CLASS_NOT_EXIST);
        }
        SmsWnsInformationConsult smsWnsInformationConsult = new SmsWnsInformationConsult();
        BeanUtils.copyProperties(addReq,smsWnsInformationConsult);
        smsWnsInformationConsult.setUserId(userId);
        smsWnsInformationConsultMapper.insert(smsWnsInformationConsult);
        return CommonResult.success();
    }

    @Override
    public ResponseResult deletedInformationConsult(SmsWnsInformationConsultReq deletedReq) {
        if (isNullOrEmpty(deletedReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsWnsInformationConsult smsWnsInformationConsult = smsWnsInformationConsultMapper.selectById(deletedReq.getId());
        if (isNullOrEmpty(smsWnsInformationConsult)) {
            return CommonResult.failed(CommonCodeEnum.INFORMATION_CONSULT_NOT_EXIST);
        }
        smsWnsInformationConsultMapper.deleteById(deletedReq.getId());
        return CommonResult.success();
    }

    @Override
    public ResponseResult updateInformationConsult(SmsWnsInformationConsultReq updateReq) {
        if (isNullOrEmpty(updateReq.getId(),updateReq.getCollegeId(),updateReq.getCollegeName(),updateReq.getMajorName(),updateReq.getMajorId(),updateReq.getGradeId(),
                updateReq.getGradeName(),updateReq.getClassId(),updateReq.getClassName(),updateReq.getQrCode(),updateReq.getQrNumber())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsWnsInformationConsult smsWnsInformationConsult = smsWnsInformationConsultMapper.selectById(updateReq.getId());
        if (isNullOrEmpty(smsWnsInformationConsult)) {
            return CommonResult.failed(CommonCodeEnum.INFORMATION_CONSULT_NOT_EXIST);
        }
        List<SmsWnsInformationConsult> informationConsultList = smsWnsInformationConsultMapper.selectList(new LambdaQueryWrapper<SmsWnsInformationConsult>()
                .eq(SmsWnsInformationConsult::getCollegeId, updateReq.getCollegeId())
                .eq(SmsWnsInformationConsult::getMajorId, updateReq.getMajorId())
                .eq(SmsWnsInformationConsult::getGradeId, updateReq.getGradeId())
                .eq(SmsWnsInformationConsult::getClassId, updateReq.getClassId())
                .ne(SmsWnsInformationConsult::getId, updateReq.getId()));
        if (!informationConsultList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INFORMATION_CONSULT_EXIST);
        }
        //校验院 专业 年级 班级
        QueryWrapper<SmsOrgStructure> orgWrapper = new QueryWrapper<>();
        List<SmsOrgStructure> orgList = orgStructureMapper.selectList(orgWrapper);
        orgWrapper.lambda().eq(SmsOrgStructure::getOrgName, updateReq.getCollegeName());
        SmsOrgStructure collegeOrg = orgStructureMapper.selectOne(orgWrapper);
        if (collegeOrg == null) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_COLLEGE_NOT_EXIST);
        }
        List<Node> nodeList = new ArrayList<>();
        for (SmsOrgStructure structure : orgList) {
            Node node = new Node();
            BeanUtils.copyProperties(structure, node);
            nodeList.add(node);
        }
        Node collegeNode = nodeTreeUtil.getChildNodesTree(nodeList, collegeOrg.getId());
        List<Node> childNode = collegeNode.getChildNodeList();
        List<Node> majorNode = childNode.stream()
                .filter(node -> node.getOrgName().equals(updateReq.getMajorName()))
                .collect(Collectors.toList());
        if (majorNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_MAJOR_NOT_EXIST);
        }
        List<Node> gradeNode = majorNode.get(0).getChildNodeList().stream()
                .filter(node -> node.getOrgName().equals(updateReq.getGradeName()))
                .collect(Collectors.toList());
        if (gradeNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_GRADE_NOT_EXIST);
        }
        List<Node> classNode = gradeNode.get(0).getChildNodeList().stream()
                .filter(node -> node.getOrgName().equals(updateReq.getClassName()))
                .collect(Collectors.toList());
        if (classNode.size() < 1) {
            return CommonResult.failed(CommonCodeEnum.DORMITORY_ORG_CLASS_NOT_EXIST);
        }
        BeanUtils.copyProperties(updateReq,smsWnsInformationConsult);
        smsWnsInformationConsultMapper.updateById(smsWnsInformationConsult);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getInformationConsultDetail(String id) {
        if (isNullOrEmpty(id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsWnsInformationConsult smsWnsInformationConsult = smsWnsInformationConsultMapper.selectById(id);
        if (isNullOrEmpty(smsWnsInformationConsult)) {
            return CommonResult.failed(CommonCodeEnum.INFORMATION_CONSULT_NOT_EXIST);
        }
        SmsWnsInformationConsultResp smsWnsInformationConsultResp = new SmsWnsInformationConsultResp();
        BeanUtils.copyProperties(smsWnsInformationConsult,smsWnsInformationConsultResp);
        //获取班主任的用户信息
        List<SmsUser> assistantUserList = assistantUtil.getAssistantUserInfo(smsWnsInformationConsult.getClassId());
        if (!assistantUserList.isEmpty()) {
            SmsUser smsUser = assistantUserList.get(0);
            UserInfoResp userInfoResp = new UserInfoResp();
            BeanUtils.copyProperties(smsUser,userInfoResp);
            smsWnsInformationConsultResp.setClassTeacherInfo(userInfoResp);
        }

        return CommonResult.success(smsWnsInformationConsultResp);
    }

    @Override
    public ResponseResult getInformationConsultList(String collegeId, String majorId, String gradeId, String classId, String classTeacher, Integer pageNum, Integer pageSize) {
        Page<SmsWnsInformationConsult> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<SmsWnsInformationConsult> informationConsultLambdaQueryWrapper = new LambdaQueryWrapper<SmsWnsInformationConsult>()
                .orderByDesc(SmsWnsInformationConsult::getCreateTime);

        if (!isNullOrEmpty(collegeId)) {
            informationConsultLambdaQueryWrapper.eq(SmsWnsInformationConsult::getCollegeId,collegeId);
        }
        if (!isNullOrEmpty(majorId)) {
            informationConsultLambdaQueryWrapper.eq(SmsWnsInformationConsult::getMajorId,majorId);
        }
        if (!isNullOrEmpty(gradeId)) {
            informationConsultLambdaQueryWrapper.eq(SmsWnsInformationConsult::getGradeId,gradeId);
        }
        if (!isNullOrEmpty(classId)) {
            informationConsultLambdaQueryWrapper.eq(SmsWnsInformationConsult::getClassId,classId);
        }

//        if (!isNullOrEmpty(classTeacher)) {
//            informationConsultLambdaQueryWrapper.eq(SmsWnsInformationConsult::getClassId,classId);
//        }
        smsWnsInformationConsultMapper.selectPage(page,informationConsultLambdaQueryWrapper);
        List<SmsWnsInformationConsultResp> informationConsultList = page.getRecords()
                .stream()
                .map(smsWnsInformationConsult -> {
                    SmsWnsInformationConsultResp smsWnsInformationConsultResp = new SmsWnsInformationConsultResp();
                    BeanUtils.copyProperties(smsWnsInformationConsult,smsWnsInformationConsultResp);
                    //获取班主任的用户信息
                    List<SmsUser> assistantUserList = assistantUtil.getAssistantUserInfo(smsWnsInformationConsult.getClassId());
                    if (!assistantUserList.isEmpty()) {
                        SmsUser smsUser = assistantUserList.get(0);
                        UserInfoResp userInfoResp = new UserInfoResp();
                        BeanUtils.copyProperties(smsUser,userInfoResp);
                        smsWnsInformationConsultResp.setClassTeacherInfo(userInfoResp);
                    }
                    return smsWnsInformationConsultResp;
                })
                .collect(Collectors.toList());
        return CommonResult.success(informationConsultList,(int)page.getTotal());
    }

    @Override
    public ResponseResult getMyInformationConsult(String userId) {
        SmsWnsMyInformationConsultResp smsWnsMyInformationConsultResp = new SmsWnsMyInformationConsultResp();
        List<SmsUserStudentRelation> smsUserStudentRelationList = smsUserStudentRelationMapper.selectList(new LambdaQueryWrapper<SmsUserStudentRelation>()
                .eq(SmsUserStudentRelation::getUserId, userId));
        if (smsUserStudentRelationList.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.STUDENT_NOT_EXIST);
        }
        String stuId = smsUserStudentRelationList.get(0).getStuId();
        SmsStudentInfo smsStudentInfo = smsStudentInfoMapper.selectById(stuId);
        if (isNullOrEmpty(smsStudentInfo)) {
            return CommonResult.failed(CommonCodeEnum.STUDENT_NOT_EXIST);
        }
        List<SmsWnsInformationConsult> consultList = smsWnsInformationConsultMapper.selectList(new LambdaQueryWrapper<SmsWnsInformationConsult>()
                .eq(SmsWnsInformationConsult::getCollegeName, smsStudentInfo.getStuCollege())
                .eq(SmsWnsInformationConsult::getMajorName, smsStudentInfo.getStuMajor())
                .eq(SmsWnsInformationConsult::getGradeName, smsStudentInfo.getStuGrade())
                .eq(SmsWnsInformationConsult::getClassName, smsStudentInfo.getStuClass()));
        if (consultList.isEmpty()) {
            return CommonResult.success(smsWnsMyInformationConsultResp);
        }
        SmsWnsInformationConsult smsWnsInformationConsult = consultList.get(0);
        //获取班主任的用户信息
        List<SmsUser> assistantUserList = assistantUtil.getAssistantUserInfo(smsWnsInformationConsult.getClassId());
        if (!assistantUserList.isEmpty()) {
            SmsUser smsUser = assistantUserList.get(0);
            UserInfoResp userInfoResp = new UserInfoResp();
            BeanUtils.copyProperties(smsUser,userInfoResp);
            smsWnsMyInformationConsultResp.setClassTeacherInfo(userInfoResp);
        }
        BeanUtils.copyProperties(smsWnsInformationConsult,smsWnsMyInformationConsultResp);
        smsWnsMyInformationConsultResp.setId(smsWnsInformationConsult.getId());
        smsWnsMyInformationConsultResp.setQrCode(smsWnsInformationConsult.getQrCode());
        smsWnsMyInformationConsultResp.setQrNumber(smsWnsInformationConsult.getQrNumber());
        return CommonResult.success(smsWnsMyInformationConsultResp);
    }
}
